package com.zx.mes.hyl.upms.service.impl;

import com.zx.mes.hyl.upms.dao.UserRepository;
import com.zx.mes.hyl.upms.model.Trole;
import com.zx.mes.hyl.upms.model.Tuser;
import com.zx.mes.hyl.upms.pagemodel.User;
import com.zx.mes.hyl.upms.service.RoleSecurityServiceI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author hyl
 * @date 2017-12-4
 */
@Service
public class RoleSecurityServiceImpl implements RoleSecurityServiceI {

    @Autowired
    private UserRepository userRepository;

    @Override
    public List<SimpleGrantedAuthority> findAllRoleByUser(User user) {

        Tuser tuser=userRepository.getByUserId(user.getId());

        if (tuser==null){
            throw new UsernameNotFoundException("用户名不存在");
        }

        List<SimpleGrantedAuthority> authorities=new ArrayList<>();

        if (tuser.getTroles()!=null && tuser.getTroles().size()>0){
            for (Trole trole:tuser.getTroles()){
                authorities.add(new SimpleGrantedAuthority(trole.getName()));
            }
        }
        return authorities;
    }


}
